//
//  HMRefreshControl.swift
//  01-自定义刷新控件
//
//  Created by apple on 16/8/15.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
// 刷新控件的状态
enum HMRefreshControlState: Int {
    // 正常
    case Normal = 0
    // 下拉中
    case Pulling = 1
    // 刷新中
    case Refreshing = 2
}

// 控件的高度
private let HMRefreshControlH: CGFloat = 50

class HMRefreshControl: UIControl {
    // 记录滑动视图
    var scrollView: UIScrollView?
    // 记录状态
    var hmState:HMRefreshControlState = .Normal{
        didSet{
            switch hmState{
            case .Normal:
                messageLabel.text = "正常"
                // 只有上个状态为刷新中 才减去scrollView 顶部滑动的距离
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.scrollView?.contentInset.top -= HMRefreshControlH
                        }, completion: { (_) -> Void in
                            
                    })
                }

            case .Pulling:
                messageLabel.text = "下拉中"
            case .Refreshing:
                messageLabel.text = "刷新中"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    // 只有当前状态为刷新中 才加上scrollView 顶部滑动的距离
                    self.scrollView?.contentInset.top += HMRefreshControlH
                    }, completion: { (_) -> Void in
                        // 告知外界刷新
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                })
            }
        }
    }

    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -HMRefreshControlH, width: SCREENW, height: HMRefreshControlH))
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // 供外界调用 结束刷新
    func endRefreshing(){
        hmState = .Normal
    }
    
    // 该控件将要加载谁身上
    override func willMoveToSuperview(newSuperview: UIView?) {
       
        // 判断他是否为nil  而且是否可以转成UIScrollView
        guard let scrollView = newSuperview as? UIScrollView else{
            return
        }
        // 赋值 
        self.scrollView = scrollView
        // 使用KVO 注册观察者
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
    }
    // 观察者中实现
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        // 记录scrollView滚动
        let contentOffsetY = self.scrollView!.contentOffset.y
        // 顶部滑动的距离
        let contentInsetTop = self.scrollView!.contentInset.top
        // 代表拖动中
        if scrollView!.dragging {
            if contentOffsetY > -contentInsetTop - HMRefreshControlH && hmState == .Pulling{
                print("正常")
                hmState = .Normal
                
            }else if contentOffsetY <= -contentInsetTop - HMRefreshControlH && hmState == .Normal{
                print("下拉中")
                hmState = .Pulling
                
            }
            
        }else {
            // 松手了
            if hmState == .Pulling {
                hmState = .Refreshing
                print("刷新中")
            }
        }
    }

    
    // MARK: - 设置视图
    private func setupUI(){
        backgroundColor = UIColor.orangeColor()
        // 添加控件
        addSubview(messageLabel)
        // 添加约束
        // 取消translatesAutoresizingMaskIntoConstraints
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        // 添加约束
        /*
            - 01 约束的对象
            - 02 约束的条件
            - 03 关系
            - 04 相对的对象
            - 05 约束的条件
            - 06 倍数
            - 07 偏移量
        */
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
    }
    
    // MARK: - 懒加载控件
    private lazy var messageLabel: UILabel = {
        let lab = UILabel()
        lab.text = "正常"
        lab.textColor = UIColor.whiteColor()
        lab.font = UIFont.systemFontOfSize(15)
        return lab
    }()
    // KVO移除
    deinit{
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}

extension HMRefreshControl: UIScrollViewDelegate {
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
    }
}
